<template>
  <div class="emergency-shift-container">
    <!-- 页面头部 -->
    <div class="emergency-header">
      <div class="header-content">
        <div class="ancient-title">紧急调班处理</div>
        <div class="header-subtitle">阴曹地府 · 突发情况应急调度</div>
      </div>
    </div>

    <!-- 路由信息 -->
    <div class="route-info">
      <a-breadcrumb>
        <a-breadcrumb-item
          ><router-link to="/management"><ApartmentOutlined />机构管理</router-link></a-breadcrumb-item
        >
        <a-breadcrumb-item
          ><router-link to="/management/duty-schedule"><ScheduleOutlined />值班排班系统</router-link></a-breadcrumb-item
        >
        <a-breadcrumb-item><AlertOutlined />{{ $route.meta.title }}</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <!-- 紧急状态概览 -->
    <div class="emergency-overview">
      <a-alert v-if="hasEmergency" :message="emergencyStatus.message" :description="emergencyStatus.description" type="error" show-icon closable style="margin-bottom: 20px">
        <template #action>
          <a-button @click="handleEmergency" type="primary" danger size="small"> 立即处理 </a-button>
        </template>
      </a-alert>
    </div>

    <a-row :gutter="24">
      <!-- 左侧：紧急调班申请 -->
      <a-col :xs="24" :lg="16">
        <a-card title="紧急调班申请" :bordered="false">
          <template #extra>
            <a-space>
              <a-button type="primary" @click="showEmergencyRequestModal"> <PlusOutlined />发起调班 </a-button>
              <a-button @click="refreshData"> <ReloadOutlined />刷新 </a-button>
            </a-space>
          </template>

          <!-- 筛选区域 -->
          <div class="filter-section">
            <a-row :gutter="16">
              <a-col :span="6">
                <a-select v-model:value="filterUrgency" placeholder="紧急程度" style="width: 100%" allow-clear>
                  <a-select-option value="">全部</a-select-option>
                  <a-select-option value="critical">极紧急</a-select-option>
                  <a-select-option value="high">高</a-select-option>
                  <a-select-option value="medium">中</a-select-option>
                </a-select>
              </a-col>
              <a-col :span="6">
                <a-select v-model:value="filterStatus" placeholder="处理状态" style="width: 100%" allow-clear>
                  <a-select-option value="">全部状态</a-select-option>
                  <a-select-option value="pending">待处理</a-select-option>
                  <a-select-option value="processing">处理中</a-select-option>
                  <a-select-option value="resolved">已解决</a-select-option>
                  <a-select-option value="rejected">已拒绝</a-select-option>
                </a-select>
              </a-col>
              <a-col :span="6">
                <a-select v-model:value="filterDepartment" placeholder="申请部门" style="width: 100%" allow-clear>
                  <a-select-option value="">全部部门</a-select-option>
                  <a-select-option v-for="dept in allDepartments" :key="dept.id" :value="dept.name">
                    {{ dept.name }}
                  </a-select-option>
                </a-select>
              </a-col>
              <a-col :span="6">
                <a-input-search v-model:value="searchText" placeholder="搜索申请" @search="handleSearch" />
              </a-col>
            </a-row>
          </div>

          <!-- 调班申请列表 -->
          <div class="emergency-requests">
            <div v-for="request in filteredRequests" :key="request.id" class="request-item">
              <div class="request-header">
                <div class="request-info">
                  <h4 class="request-title">{{ request.title }}</h4>
                  <div class="request-meta">
                    <a-tag :color="getUrgencyColor(request.urgency)">{{ getUrgencyText(request.urgency) }}</a-tag>
                    <a-tag :color="getStatusColor(request.status)">{{ getStatusText(request.status) }}</a-tag>
                    <span class="request-time">{{ request.createTime }}</span>
                  </div>
                </div>
                <div class="request-actions">
                  <a-dropdown>
                    <a-button type="text"><MoreOutlined /></a-button>
                    <template #overlay>
                      <a-menu>
                        <a-menu-item @click="viewRequest(request)"> <EyeOutlined />查看详情 </a-menu-item>
                        <a-menu-item @click="approveRequest(request)" v-if="request.status === 'pending'"> <CheckOutlined />批准申请 </a-menu-item>
                        <a-menu-item @click="rejectRequest(request)" v-if="request.status === 'pending'"> <CloseOutlined />拒绝申请 </a-menu-item>
                        <a-menu-divider />
                        <a-menu-item @click="assignPersonnel(request)" v-if="request.status === 'processing'"> <UserOutlined />分配人员 </a-menu-item>
                      </a-menu>
                    </template>
                  </a-dropdown>
                </div>
              </div>

              <div class="request-content">
                <div class="request-description">{{ request.description }}</div>
                <div class="request-details">
                  <div class="detail-item">
                    <span class="detail-label">申请部门：</span>
                    <span class="detail-value">{{ request.department }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">申请人：</span>
                    <span class="detail-value">{{ request.applicant }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">需要时间：</span>
                    <span class="detail-value">{{ request.requiredTime }}</span>
                  </div>
                </div>
              </div>

              <div class="request-progress" v-if="request.status === 'processing'">
                <div class="progress-info">
                  <span class="progress-label">处理进度</span>
                  <span class="progress-percentage">{{ request.progress }}%</span>
                </div>
                <a-progress :percent="request.progress" size="small" :show-info="false" />
              </div>

              <div class="request-timeline" v-if="request.timeline && request.timeline.length > 0">
                <h5>处理记录</h5>
                <a-timeline size="small">
                  <a-timeline-item v-for="item in request.timeline" :key="item.id" :color="item.color">
                    <div class="timeline-content">
                      <div class="timeline-action">{{ item.action }}</div>
                      <div class="timeline-time">{{ item.time }}</div>
                      <div class="timeline-operator">操作人：{{ item.operator }}</div>
                    </div>
                  </a-timeline-item>
                </a-timeline>
              </div>
            </div>

            <div v-if="filteredRequests.length === 0" class="no-requests">
              <a-empty description="暂无紧急调班申请" />
            </div>
          </div>
        </a-card>
      </a-col>

      <!-- 右侧：应急工具和统计 -->
      <a-col :xs="24" :lg="8">
        <a-space direction="vertical" size="large" style="width: 100%">
          <!-- 应急响应时间 -->
          <a-card title="应急响应统计" size="small" :bordered="false">
            <div class="response-stats">
              <div class="stat-item">
                <span class="stat-label">平均响应时间：</span>
                <span class="stat-value">{{ responseStats.avgResponseTime }}分钟</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">本月申请数：</span>
                <span class="stat-value">{{ responseStats.monthlyRequests }}件</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">解决率：</span>
                <span class="stat-value">{{ responseStats.resolutionRate }}%</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">满意度：</span>
                <span class="stat-value">{{ responseStats.satisfaction }}%</span>
              </div>
            </div>
          </a-card>

          <!-- 可用人员 -->
          <a-card title="可调配人员" size="small" :bordered="false">
            <div class="available-personnel">
              <div v-for="person in availablePersonnel" :key="person.id" class="personnel-item">
                <div class="person-info">
                  <a-avatar :src="person.avatar" size="small">{{ person.name.charAt(0) }}</a-avatar>
                  <div class="person-details">
                    <div class="person-name">{{ person.name }}</div>
                    <div class="person-dept">{{ person.department }}</div>
                  </div>
                </div>
                <div class="person-status">
                  <a-tag :color="person.available ? 'green' : 'red'" size="small">
                    {{ person.available ? '可用' : '忙碌' }}
                  </a-tag>
                </div>
              </div>
            </div>
          </a-card>

          <!-- 应急预案 -->
          <a-card title="应急预案" size="small" :bordered="false">
            <div class="emergency-plans">
              <div v-for="plan in emergencyPlans" :key="plan.id" class="plan-item">
                <div class="plan-info">
                  <h5 class="plan-name">{{ plan.name }}</h5>
                  <p class="plan-description">{{ plan.description }}</p>
                </div>
                <div class="plan-action">
                  <a-button type="link" size="small" @click="activatePlan(plan)"> 启动 </a-button>
                </div>
              </div>
            </div>
          </a-card>

          <!-- 快速操作 -->
          <a-card title="快速操作" size="small" :bordered="false">
            <div class="quick-actions">
              <a-button block @click="emergencyBroadcast" style="margin-bottom: 8px" danger> <SoundOutlined />紧急广播 </a-button>
              <a-button block @click="autoAssign" style="margin-bottom: 8px"> <ThunderboltOutlined />自动分配 </a-button>
              <a-button block @click="generateReport"> <FileTextOutlined />生成报告 </a-button>
            </div>
          </a-card>
        </a-space>
      </a-col>
    </a-row>

    <!-- 发起紧急调班弹窗 -->
    <a-modal v-model:open="emergencyRequestModalVisible" title="发起紧急调班申请" @ok="handleEmergencyRequest" width="600px">
      <a-form ref="requestFormRef" :model="requestForm" :rules="requestRules" layout="vertical">
        <a-form-item label="申请标题" name="title">
          <a-input v-model:value="requestForm.title" placeholder="请输入申请标题" />
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="紧急程度" name="urgency">
              <a-select v-model:value="requestForm.urgency" placeholder="选择程度">
                <a-select-option value="critical">极紧急</a-select-option>
                <a-select-option value="high">高</a-select-option>
                <a-select-option value="medium">中</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="申请部门" name="department">
              <a-select v-model:value="requestForm.department" placeholder="选择部门">
                <a-select-option v-for="dept in allDepartments" :key="dept.id" :value="dept.name">
                  {{ dept.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="申请人" name="applicant">
              <a-input v-model:value="requestForm.applicant" placeholder="申请人姓名" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="需要时间" name="requiredTime">
          <a-input v-model:value="requestForm.requiredTime" placeholder="例如：今日18:00-明日08:00" />
        </a-form-item>

        <a-form-item label="申请原因" name="description">
          <a-textarea v-model:value="requestForm.description" placeholder="详细说明紧急调班的原因" :rows="4" />
        </a-form-item>

        <a-form-item label="联系方式" name="contact">
          <a-input v-model:value="requestForm.contact" placeholder="紧急联系方式" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { HomeOutlined, ApartmentOutlined, ScheduleOutlined, AlertOutlined, PlusOutlined, ReloadOutlined, MoreOutlined, EyeOutlined, CheckOutlined, CloseOutlined, UserOutlined, SoundOutlined, ThunderboltOutlined, FileTextOutlined } from '@ant-design/icons-vue'

// 响应式数据
const searchText = ref('')
const filterUrgency = ref('')
const filterStatus = ref('')
const filterDepartment = ref('')
const emergencyRequestModalVisible = ref(false)
const requestFormRef = ref()

// 紧急状态
const hasEmergency = ref(true)
const emergencyStatus = reactive({
  message: '紧急情况：第三殿宋帝王突发急症，需要立即调配人员接替值班',
  description: '预计影响时间：12小时，需要紧急调配2名高级仙官接替工作'
})

// 部门数据
const allDepartments = ref([
  { id: 1, name: '第一殿秦广王府' },
  { id: 2, name: '第二殿楚江王府' },
  { id: 3, name: '第三殿宋帝王府' },
  { id: 5, name: '第五殿阎罗王府' },
  { id: 10, name: '第十殿转轮王府' }
])

// 紧急调班申请数据
const requests = ref([
  {
    id: 1,
    title: '第三殿王级仙官紧急替换',
    urgency: 'critical',
    status: 'processing',
    department: '第三殿宋帝王府',
    applicant: '副王李太乙',
    requiredTime: '即日起-明日18:00',
    description: '宋帝王突发急症，需要立即安排高级仙官接替审判工作',
    createTime: '30分钟前',
    progress: 65,
    contact: '急召专线001',
    timeline: [
      { id: 1, action: '申请提交', time: '30分钟前', operator: '副王李太乙', color: 'blue' },
      { id: 2, action: '申请批准', time: '25分钟前', operator: '人事司', color: 'green' },
      { id: 3, action: '人员调配中', time: '15分钟前', operator: '调度中心', color: 'orange' }
    ]
  },
  {
    id: 2,
    title: '第五殿夜班人员不足',
    urgency: 'high',
    status: 'pending',
    department: '第五殿阎罗王府',
    applicant: '判官王无邪',
    requiredTime: '今日20:00-明日08:00',
    description: '夜班人员因紧急任务外出，需要临时调配2名执法仙官',
    createTime: '1小时前',
    progress: 0,
    contact: '阎罗殿直线',
    timeline: []
  },
  {
    id: 3,
    title: '转轮王府系统维护支援',
    urgency: 'medium',
    status: 'resolved',
    department: '第十殿转轮王府',
    applicant: '技术主管张道灵',
    requiredTime: '昨日22:00-今日06:00',
    description: '轮回系统升级需要技术人员通宵维护，申请加班补贴和后勤支持',
    createTime: '1天前',
    progress: 100,
    contact: '转轮殿技术组',
    timeline: [
      { id: 1, action: '申请提交', time: '1天前', operator: '张道灵', color: 'blue' },
      { id: 2, action: '申请批准', time: '23小时前', operator: '人事司', color: 'green' },
      { id: 3, action: '支援完成', time: '6小时前', operator: '后勤部', color: 'green' }
    ]
  }
])

// 响应统计
const responseStats = reactive({
  avgResponseTime: 15,
  monthlyRequests: 8,
  resolutionRate: 94,
  satisfaction: 96
})

// 可用人员
const availablePersonnel = ref([
  { id: 1, name: '楚江王', department: '第二殿', available: true, avatar: '' },
  { id: 2, name: '五官王', department: '第四殿', available: true, avatar: '' },
  { id: 3, name: '判官赵德', department: '第一殿', available: false, avatar: '' },
  { id: 4, name: '执法官钱进', department: '第五殿', available: true, avatar: '' }
])

// 应急预案
const emergencyPlans = ref([
  { id: 1, name: '王级仙官替换预案', description: '当王级仙官无法履职时的应急替换方案' },
  { id: 2, name: '夜班人员不足预案', description: '夜班期间人员短缺的应急调配方案' },
  { id: 3, name: '系统故障预案', description: '关键系统故障时的应急处理方案' },
  { id: 4, name: '天灾应急预案', description: '自然灾害影响正常值班的应急方案' }
])

// 表单数据
const requestForm = reactive({
  title: '',
  urgency: '',
  department: '',
  applicant: '',
  requiredTime: '',
  description: '',
  contact: ''
})

// 表单验证规则
const requestRules = {
  title: [{ required: true, message: '请输入申请标题', trigger: 'blur' }],
  urgency: [{ required: true, message: '请选择紧急程度', trigger: 'change' }],
  department: [{ required: true, message: '请选择申请部门', trigger: 'change' }],
  applicant: [{ required: true, message: '请输入申请人', trigger: 'blur' }],
  requiredTime: [{ required: true, message: '请输入需要时间', trigger: 'blur' }],
  description: [{ required: true, message: '请输入申请原因', trigger: 'blur' }]
}

// 计算属性
const filteredRequests = computed(() => {
  let result = requests.value

  if (filterUrgency.value) {
    result = result.filter((request) => request.urgency === filterUrgency.value)
  }

  if (filterStatus.value) {
    result = result.filter((request) => request.status === filterStatus.value)
  }

  if (filterDepartment.value) {
    result = result.filter((request) => request.department === filterDepartment.value)
  }

  if (searchText.value) {
    result = result.filter((request) => request.title.toLowerCase().includes(searchText.value.toLowerCase()))
  }

  return result
})

// 方法
const getUrgencyColor = (urgency) => {
  const colors = { critical: 'red', high: 'orange', medium: 'blue' }
  return colors[urgency] || 'default'
}

const getUrgencyText = (urgency) => {
  const texts = { critical: '极紧急', high: '高', medium: '中' }
  return texts[urgency] || urgency
}

const getStatusColor = (status) => {
  const colors = { pending: 'orange', processing: 'blue', resolved: 'green', rejected: 'red' }
  return colors[status] || 'default'
}

const getStatusText = (status) => {
  const texts = { pending: '待处理', processing: '处理中', resolved: '已解决', rejected: '已拒绝' }
  return texts[status] || status
}

const handleEmergency = () => {
  hasEmergency.value = false
  message.success('紧急情况处理程序已启动')
}

const showEmergencyRequestModal = () => {
  Object.assign(requestForm, {
    title: '',
    urgency: '',
    department: '',
    applicant: '',
    requiredTime: '',
    description: '',
    contact: ''
  })
  emergencyRequestModalVisible.value = true
}

const handleEmergencyRequest = async () => {
  try {
    await requestFormRef.value.validate()
    const newRequest = {
      id: Date.now(),
      ...requestForm,
      status: 'pending',
      progress: 0,
      createTime: '刚刚',
      timeline: []
    }
    requests.value.unshift(newRequest)
    message.success('紧急调班申请提交成功')
    emergencyRequestModalVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const viewRequest = (request) => {
  message.info(`查看申请详情: ${request.title}`)
}

const approveRequest = (request) => {
  request.status = 'processing'
  request.progress = 30
  message.success('申请已批准，开始处理')
}

const rejectRequest = (request) => {
  request.status = 'rejected'
  message.info('申请已拒绝')
}

const assignPersonnel = (request) => {
  message.info(`为申请分配人员: ${request.title}`)
}

const activatePlan = (plan) => {
  message.success(`应急预案"${plan.name}"已启动`)
}

const emergencyBroadcast = () => {
  message.info('紧急广播已发送到所有部门')
}

const autoAssign = () => {
  message.info('自动分配程序启动中...')
}

const generateReport = () => {
  message.info('紧急调班报告生成中...')
}

const refreshData = () => {
  message.success('数据已刷新')
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

onMounted(() => {
  // 页面加载时的初始化逻辑
})
</script>

<style lang="scss" scoped>
.emergency-shift-container {
  padding: 24px;

  .emergency-header {
    text-align: center;
    margin-bottom: 32px;

    .header-content {
      .ancient-title {
        font-size: 32px;
        font-weight: bold;
        color: $secondary-color;
        margin-bottom: 8px;
        text-shadow: 0 0 20px rgba(212, 153, 10, 0.3);
      }

      .header-subtitle {
        font-size: 16px;
        color: $text-secondary;
        letter-spacing: 2px;
      }
    }
  }

  .route-info {
    margin-bottom: 24px;
    padding: 12px 16px;
    border-radius: 8px;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(212, 153, 10, 0.2);
  }

  .emergency-overview {
    margin-bottom: 24px;
  }

  .filter-section {
    margin-bottom: 20px;
    padding: 16px;
    border-radius: 8px;
    border: 1px solid rgba(212, 153, 10, 0.2);
  }

  .emergency-requests {
    .request-item {
      margin-bottom: 20px;
      padding: 20px;
      border: 1px solid rgba(212, 153, 10, 0.2);
      border-radius: 12px;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
      }

      .request-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 16px;

        .request-info {
          flex: 1;

          .request-title {
            margin: 0 0 8px 0;
            color: $primary-color;
            font-size: 18px;
            font-weight: bold;
          }

          .request-meta {
            display: flex;
            align-items: center;
            gap: 8px;

            .request-time {
              color: $text-secondary;
              font-size: 14px;
            }
          }
        }
      }

      .request-content {
        margin-bottom: 16px;

        .request-description {
          color: $text-primary;
          line-height: 1.6;
          margin-bottom: 12px;
        }

        .request-details {
          display: flex;
          gap: 24px;

          .detail-item {
            .detail-label {
              color: $text-secondary;
              font-size: 14px;
            }

            .detail-value {
              color: $text-primary;
              font-size: 14px;
              font-weight: 500;
            }
          }
        }
      }

      .request-progress {
        margin-bottom: 16px;

        .progress-info {
          display: flex;
          justify-content: space-between;
          margin-bottom: 8px;

          .progress-label {
            color: $text-secondary;
            font-size: 14px;
          }

          .progress-percentage {
            color: $secondary-color;
            font-weight: bold;
            font-size: 14px;
          }
        }
      }

      .request-timeline {
        h5 {
          margin: 0 0 12px 0;
          color: $primary-color;
          font-size: 14px;
          font-weight: bold;
        }

        .timeline-content {
          .timeline-action {
            font-size: 14px;
            color: $text-primary;
            font-weight: 500;
            margin-bottom: 4px;
          }

          .timeline-time {
            font-size: 12px;
            color: $text-secondary;
            margin-bottom: 2px;
          }

          .timeline-operator {
            font-size: 12px;
            color: $text-secondary;
          }
        }
      }
    }

    .no-requests {
      text-align: center;
      padding: 40px;
    }
  }

  .response-stats {
    .stat-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;

      .stat-label {
        color: $text-secondary;
        font-size: 14px;
      }

      .stat-value {
        color: $secondary-color;
        font-weight: bold;
        font-size: 14px;
      }
    }
  }

  .available-personnel {
    .personnel-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 0;
      border-bottom: 1px solid rgba(212, 153, 10, 0.1);

      &:last-child {
        border-bottom: none;
      }

      .person-info {
        display: flex;
        align-items: center;
        gap: 8px;

        .person-details {
          .person-name {
            font-size: 14px;
            color: $text-primary;
            margin-bottom: 2px;
          }

          .person-dept {
            font-size: 12px;
            color: $text-secondary;
          }
        }
      }
    }
  }

  .emergency-plans {
    .plan-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid rgba(212, 153, 10, 0.1);

      &:last-child {
        border-bottom: none;
      }

      .plan-info {
        flex: 1;

        .plan-name {
          margin: 0 0 4px 0;
          color: $primary-color;
          font-size: 14px;
          font-weight: bold;
        }

        .plan-description {
          margin: 0;
          color: $text-secondary;
          font-size: 12px;
        }
      }
    }
  }

  .quick-actions {
    .ant-btn {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      gap: 8px;
    }
  }

  :deep(.ant-card) {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    border: 1px solid rgba(212, 153, 10, 0.2);
    border-radius: 12px;
  }

  :deep(.ant-card-head) {
    border-bottom: 1px solid rgba(212, 153, 10, 0.2);
  }
}
</style>
